package com.cloudlead.plugin.security.service.impl;

import com.cloudlead.common.lang.Messages;
import com.cloudlead.common.lang.service.AbstractBaseService;
import com.cloudlead.plugin.security.BusinessModules;
import com.cloudlead.plugin.security.service.CodeService;
import com.cloudlead.utils.cache.CacheService;
import com.cloudlead.utils.sms.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("codeService")
public class CodeServiceImpl extends AbstractBaseService implements CodeService {

    public static final String CODE_CACHE = "security_code_";
    public static final String CODE_RETRY_CACHE = "security_code_retry";
    public static final int CODE_EXP_SECONDS = 600;
    public static final int CODE_EXP_RETRY_SECONDS = 60;

    @Autowired
    private SmsService smsService;

    @Autowired
    private CacheService cacheService;

    public CodeServiceImpl() {
        super(BusinessModules.ScUser);
    }

    @Override
    public void addCode(String mobile, String code) {
        cacheService.set(CODE_CACHE + mobile, code, CODE_EXP_SECONDS);
        cacheService.set(CODE_RETRY_CACHE + mobile, code, CODE_EXP_RETRY_SECONDS);
    }

    @Override
    public String getCode(String mobile) {
        return (String) cacheService.get(CODE_CACHE + mobile);
    }

    @Override
    public void sendCode(String mobile, String code) {
        smsService.sendVerificationCode(mobile, Messages.getMessage("security.authorization.code.content", code));
    }

    @Override
    public boolean hasRetry(String mobile) {
        return null == cacheService.get(CODE_RETRY_CACHE + mobile);
    }
}
